package com.dcbeida.activity.purchase;

import android.app.Activity;
import android.content.DialogInterface;
import android.support.annotation.Nullable;

import com.dcbeida.MyApplication;
import com.dcbeida.activity.store.StoreContract;
import com.dcbeida.base.BasePresenter;
import com.dcbeida.base.BaseView;
import com.dcbeida.bean.Drug;
import com.dcbeida.bean.DrugBean;
import com.dcbeida.bean.DrugBeanWithPand;
import com.dcbeida.bean.DrugInfo;
import com.dcbeida.bean.DrugInfoList;
import com.dcbeida.bean.DrugListBean;
import com.dcbeida.bean.DrugResult;
import com.dcbeida.bean.Result_Api;
import com.dcbeida.callback.DialogCallback;
import com.dcbeida.model.ModelUtils;
import com.dcbeida.utils.JsonGet;
import com.dcbeida.utils.Utils;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

public class PurchaseExitPresent implements PurchaseExitContract.Present {

    private PurchaseExitContract.View view;
    private ModelUtils utils;
    private Activity act;
    private List<DrugBeanWithPand> drugInfoList;

    private String from;

    private String fromId;

    private String invoicemoney;


    //删除的标志位
    private int deletePos;

    public PurchaseExitPresent(PurchaseExitContract.View view, Activity act) {
        this.view = view;
        this.act = act;
        utils = ModelUtils.newInstance();
        drugInfoList = new ArrayList<>();

    }

    @Override
    public void start() {

    }


    @Override
    public boolean isDrugInfoList() {
        return drugInfoList.isEmpty();
    }

    @Override
    public void addinventorydrugcodes(String drugCode) {
        JsonGet jg = new JsonGet().putopt("uid", MyApplication.user.getUid())
                .putopt("drugcodes", drugCode);
        String json = jg.tostring();
        utils.getDate("addinventorydrugcodes", json, new GetdrugcodeCallBack(act,
                DrugResult.class, lis));
    }

    @Override
    public void stockinreturn(String from, String fromid, String invoicemoney) {
        this.from = from;
        this.fromId = fromid;
        this.invoicemoney = invoicemoney;
        stockrequest();
    }

    private void stockrequest() {
        DrugBeanWithPand paramDrug = drugInfoList.get(0);
        StringBuilder codeBuilder = new StringBuilder();
        codeBuilder.append(paramDrug.getDrugcode()).append(",");
        deletePos = 0;
        for (int i = 1; i < drugInfoList.size(); i++) {
            if (drugInfoList.get(i).getDrugid() != paramDrug.getDrugid())
                break;
            else {
                deletePos = i;
                codeBuilder.append(drugInfoList.get(i).getDrugcode()).append(",");
            }
        }

        JsonGet jg = new JsonGet().putopt("uid", MyApplication.user.getUid())
                .putopt("shopid", MyApplication.user.getShopid())
                .putopt("shopname", MyApplication.user.getShopname())
                .putopt("deliviryTime", Utils.getNowTime())
                .putopt("from", from)
                .putopt("fromid", fromId)
                .putopt("invoicemoney", invoicemoney)
                .putopt("durgId", paramDrug.getDrugid())
                .putopt("quantity", paramDrug.getCount())
                .putopt("drugcodes", codeBuilder.deleteCharAt(codeBuilder.length() - 1));
        String json = jg.tostring();
        utils.getDate("stockinreturn", json, new ApiCallBack(act,
                Result_Api.class, null, "正在提交药品" + paramDrug.getDrugid() + "的盘点数据,请稍候..."));
    }

    //取消dialog 取消请求
    DialogInterface.OnCancelListener lis = new DialogInterface.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            utils.getCancel();
        }
    };


    //根据条形码查询详细信息
    class GetdrugcodeCallBack<T> extends DialogCallback<T> {

        public GetdrugcodeCallBack(Activity activity, Type type, DialogInterface.OnCancelListener listener) {
            super(activity, type, listener);
        }

        @Override
        public void onResponse(T data) {
            if (data == null || !(data instanceof DrugResult) || ((DrugResult) data).getList() == null ||
                    ((DrugResult) data).getList().size() == 0) {
                view.showTip("没有查询到此药品");
                return;
            }
            DrugBeanWithPand drugBean = ((DrugResult) data).getList().get(0);
            DrugListBean drugListBean = MyApplication.getInstance().getmDrugBean();
            if (drugListBean != null && drugListBean.getList() != null && !drugListBean.getList().isEmpty()) {
                boolean isExit = false;//是否存在在这个列表中
                for (Drug drug : drugListBean.getList()) {
                    if (drug.getDrugid() == drugBean.getDrugid())
                        isExit = true;
                }
                if (!isExit) {
                    view.showTip("药品码错误");
                    return;
                }
            }
            if (drugInfoList.contains(drugBean)) {
                view.showTip("此款药品已存在列表中...");
                return;
            }

            int pos = -1;
            int head_pos = 0;
            for (int i = 0; i < drugInfoList.size(); i++) {
                if (drugInfoList.get(i).getDrugid() == drugBean.getDrugid()) {
                    if (drugInfoList.get(i).isFirst()) {
                        head_pos = i;
                    }
                    pos = i;
                }
            }

            if (pos == -1) {
                drugBean.setFirst(true);
                drugBean.setCount(drugBean.getQuantity());
                pos = drugInfoList.size();
                head_pos = pos;
            } else {
                drugBean.setFirst(false);
                DrugBeanWithPand headInfo = drugInfoList.get(head_pos);
                int count = headInfo.getCount() + drugBean.getQuantity();
                headInfo.setCount(count);
                pos = pos + 1;
            }

            drugInfoList.add(pos, drugBean);
            view.addItem(pos, drugBean, head_pos, drugInfoList.get(head_pos));

        }


        public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
            super.onError(call, response, e);
            view.showTip("数据未请求成功,请检查网络...");


        }
    }

    //药店销售-新增销售记录 返回结果
    class ApiCallBack<T> extends DialogCallback<T> {

        public ApiCallBack(Activity activity, Class<T> tclass, DialogInterface.OnCancelListener listener, String message) {
            super(activity, tclass, listener, message);
        }

        @Override
        public void onResponse(T data) {
            if (data != null) {
                if (((Result_Api) data).getCode() == 1) {
                    drugInfoList.subList(0, deletePos + 1).clear();
                    if (drugInfoList.size() > 0) {
                        stockrequest();
                    } else {
                        view.showSuccess();
                    }
                }
            }
        }


        public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
            super.onError(call, response, e);
            view.showTip("数据未请求成功,请检查网络后再重试...");

        }
    }
}





